package ldh.database;

import java.util.List;

public class ForeignKey {

	private String columnName;
	
	private Column column;
	
	private String foreignColumnName;
	
	private Column foreignColumn;
	
	private String foreignTableName;
	
	private Table foreignTable;
	
	private Table table;

	private String tableName;
	
	private boolean isOneToOne = false;
	
	public ForeignKey(String tableName, String columnName, String foreignColumnName, String foreignTableName) {
		this.tableName = tableName;
		this.columnName = columnName;
		this.foreignTableName = foreignTableName;
		this.foreignColumnName = foreignColumnName;
	}

	public void handle(List<Column> columns) {
		for(Column c : columns) {
			if (c.getName().equals(columnName)) {
				column = c;
				c.setForeign(true);
				c.setForeignKey(this);
				System.out.println("tableName: " + tableName + ", fk:" + this);
			}
		}
	}

	public String getColumnName() {
		return columnName;
	}


	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public Table getForeignTable() {
		return foreignTable;
	}

	public void setForeignTable(Table foreignTable) {
		this.foreignTable = foreignTable;
		for (Column cc : foreignTable.getColumnList()) {
			if (cc.getName().equals(this.foreignColumnName)) {
				this.foreignColumn = cc;
				foreignTable.addMany(this);
				break;
			}
		}
	}

	public String getForeignColumnName() {
		return foreignColumnName;
	}

	public void setForeignColumnName(String foreignColumnName) {
		this.foreignColumnName = foreignColumnName;
	}

	public Column getForeignColumn() {
		return foreignColumn;
	}

	public void setForeignColumn(Column foreignColumn) {
		this.foreignColumn = foreignColumn;
	}

	public String getForeignTableName() {
		return foreignTableName;
	}

	public void setForeignTableName(String foreignTableName) {
		this.foreignTableName = foreignTableName;
	}

	public Column getColumn() {
		return column;
	}

	public void setColumn(Column column) {
		this.column = column;
	}

	public Table getTable() {
		return table;
	}

	public void setTable(Table table) {
		this.table = table;
	}

	public boolean isOneToOne() {
		return isOneToOne;
	}

	public void setOneToOne(boolean isOneToOne) {
		this.isOneToOne = isOneToOne;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public boolean equals(Object obj) {
		if (obj == null) return false;
		if (!(obj instanceof ForeignKey)) return false;
		ForeignKey other = (ForeignKey) obj;
		return tableName.equals(other.getTableName()) && columnName.equals(other.getColumnName());
	}

	public int hashCode() {
		int code = tableName.hashCode();
		code += code * 31 + columnName.hashCode();
		return code;
	}
	
}
